<template>
  <el-dialog title="新建文件夹" :visible.sync="dialogVisible" top="8vh" :before-close="cancel">
    <el-form :model="folder" label-width="95px" :rules="rules" ref="ruleForm">
      <el-form-item label="文件夹名称" prop="folderName">
        <el-input v-model="folder.folderName"></el-input>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input type="textarea" v-model="folder.folderKeyWord"></el-input>
      </el-form-item>
      <el-form-item label="上级文件夹">
        <folder-select-tree :tree-data="treeData" @onClickNode="onClickNode" :clear="clear"></folder-select-tree>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {mapState} from 'vuex'
  import FolderSelectTree from '../../../components/folderSelectTree'
  import {folderService} from '../../../service/folderService'
  import {Msg} from '../../../tools/message'

  export default {
    name: 'folderDialog',
    components: {FolderSelectTree},
    data () {
      return {
        folder: {
          folderName: '',
          folderKeyWord: '',
          parentFolder: null
        },
        rules: {
          folderName: [{required: true, message: '请输入文件夹名称', trigger: 'blur'}],
        },
        clear: false // 上级文件夹是否清空
      }
    },
    props: {
      dialogVisible: {
        type: Boolean,
        default: function () {
          return false
        }
      }
    },
    computed: mapState({
      treeData: state => state.folder.folderTree
    }),
    watch: {
      folder: function () {
        this.clear = !this.clear
      }
    },
    methods: {
      cancel () {
        this.folder = {}
        this.$emit('cancel')
        this.folder = {}
      },
      sure () {
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            this.submit()
          } else {
            return false
          }
        })
      },
      submit () {
        this.folder.userId = this.$store.getters.userInfo.userId
        if (!this.folder.parentFolder) {
          this.folder.parentFolder = this.$store.state.folder.currentPath.folderId
        }
        folderService.addFolder(this.folder).then(res => {
          if (res.data.status) {
            Msg.success(res.data.msg)
            this.$emit('sure')
          } else {
            Msg.error(res.data.msg)
          }
          this.folder = {}
        }).catch(error => {
          Msg.error('新增失败')
          this.folder = {}
        })
      },
      onClickNode (path, id) {
        this.folder.parentFolder = id
      }
    },
  }
</script>

<style lang="scss" scoped>

</style>
